package com.lry.netty01.server.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingMap {

    private static ConcurrentHashMap<Integer,Object> map  = new ConcurrentHashMap(16);
    private static Lock lock = new ReentrantLock();
    private static Condition notFull = lock.newCondition();//容器不满，生产者
    private static Condition notEmpty = lock.newCondition();//容器不空，消费者

    public static void put(Integer key,Object obj){
        try{
            lock.lock();
            Object mapObj = map.get(key);
            if(null!=mapObj){
                //如果已有此键，阻塞在此
                notFull.await();
            }
            //没有则put
            map.put(key,obj);
            //唤醒消费者
            notEmpty.signalAll();

        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static Object get(Integer key){
        Object mapObj = null;
        try{
            lock.lock();
            mapObj = map.get(key);
            if(null==mapObj){
                //拿不到该值，阻塞消费者
                notEmpty.await(3, TimeUnit.SECONDS);
            }
            mapObj = map.get(key);
            //唤醒生产者
            notFull.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        map.remove(key);
        return mapObj;
    }

}
